package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yixun.common.exception.YIXUNExceptionCode;
import com.yixun.common.exception.YIXUNUNCheckedException;
import com.yixun.common.page.Page;
import com.yixun.qfbao.api.service.CommissionService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.model.CommissionRuleParent;
import com.yixun.qfbao.model.CommissionRules;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.DateToEnum;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.PageUtil;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description
 * @Date 2017/11/27
 * @Author sangtao
 * @Computer Administrator
 */
@Service
public class CommissionServiceImpl implements CommissionService {
    private Logger logger = LoggerFactory.getLogger(CommissionServiceImpl.class);
    @Autowired
    private PartnerInfoService partnerInfoService;
    @Autowired
    private CustomerPremisesService customerPremisesService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private com.yixun.qfbao.service.CommissionService commissionService;
    @Autowired
    private CommissionRulesService commissionRulesService;
    @Autowired
    private CommissionRuleParentService commissionRuleParentService;
    @Autowired
    private PremisesService premisesService;
    @Autowired
    private IndexBasicService indexBasicService;
    @Autowired
    private CompanyRelationService companyRelationService;
    /**
    *@description  获取个人佣金 分销助手首页
    *@author sangtao
    *@date 2017/11/27
    *@param dto
    **/
    @Override
    public GetCustomerPremisesResDto getCustomerPremises(GetCustomerPremisesReqDto dto){
        GetCustomerPremisesResDto getCustomerPremisesResDto = new GetCustomerPremisesResDto();
       try {
           if(StringUtils.isBlank(dto.getUserId())){
               return getCustomerPremisesResDto;
           }
           PartnerInfo partner = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
           //如果公司不需要佣金，则直接不查询，把标识传入到下一层
           Long companyId = partner.getHigherid();
           //获取对应的代理商是否开启了启用佣金金额配置
//           Company company = companyService.selectById(companyId);
//           if(company == null) {
//        	   getCustomerPremisesResDto.setResultMsg("员工ID有误");
//               getCustomerPremisesResDto.setResult(ResultEnum.FAIL.getNo());
//               return getCustomerPremisesResDto;
//           }
           String commisionFlag = companyRelationService.searchCommisionFlag(companyId);
           CustomerPremisesDto premisesDto = customerPremisesService.selectCustomerPremisesByStaffId(
        		   partner, dto.getIsturn(), commisionFlag);
           BeanUtils.copyProperties(premisesDto, getCustomerPremisesResDto);
           getCustomerPremisesResDto.setCommissionAmount(premisesDto.getCommissionAmount() == null ?
                   BigDecimal.ZERO : new BigDecimal(premisesDto.getCommissionAmount()));
           getCustomerPremisesResDto.setResult(ResultEnum.SUCCESS.getNo());
       } catch (Exception e) {
    	   logger.error("getCustomerPremises error: {}", e);
            getCustomerPremisesResDto.setResultMsg(e.getMessage());
            getCustomerPremisesResDto.setResult(ResultEnum.FAIL.getNo());
        }
		return getCustomerPremisesResDto;
    }

    /**
     *@description  获取个人佣金 小程序首页
     **/
    @Override
    public GetCustomerPremisesWeAppResDto getCustomerPremisesWeApp(GetCustomerPremisesReqDto dto){
        GetCustomerPremisesWeAppResDto getCustomerPremisesResDto = new GetCustomerPremisesWeAppResDto();
        try {
            PartnerInfo partner = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
            Long companyId = partner.getHigherid();
            Company company = companyService.selectById(companyId);
            CustomerPremisesDto premisesDto = customerPremisesService.selectCustomerPremisesByStaffId(partner, dto.getIsturn(), company.getCommissionFlag());
            BeanUtils.copyProperties(premisesDto, getCustomerPremisesResDto);
            getCustomerPremisesResDto.setResult(ResultEnum.SUCCESS.getNo());
        } catch (Exception e) {
            logger.error("getCustomerPremises error: {}", e);
            getCustomerPremisesResDto.setResultMsg(e.getMessage());
            getCustomerPremisesResDto.setResult(ResultEnum.FAIL.getNo());
        }
        return getCustomerPremisesResDto;
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/28
    *@param dto
    **/
    @Override
    public GetPremisesCommissionResDto getPremisesCommission(GetPremisesCommissionReqDto dto){
        GetPremisesCommissionResDto getPremisesCommissionResDto = new GetPremisesCommissionResDto();
        try{
            List<CustomerPremisesDto> cpList = new ArrayList<CustomerPremisesDto>();

            List<Long> premisesIds = new ArrayList<Long>(); //项目id集合
            //获取用户选择的项目id，如选择‘全部’，则先查询所有项目id
            if(StringUtils.isNotBlank(dto.getPremisesId())){
                premisesIds.add(Long.parseLong(dto.getPremisesId()));
            }else{
                String pid =dto.getPremisesIds();
                if(StringUtils.isBlank(pid)){
                    getPremisesCommissionResDto.setResult(ResultEnum.SUCCESS.getNo());
                    getPremisesCommissionResDto.setCpList(cpList);
                    return getPremisesCommissionResDto;
                }
                String[] pids = pid.split(",");
                for(int i = 0; i < pids.length; i++){
                    premisesIds.add(Long.parseLong(pids[i]));
                }
            }

            CustomerPremisesDto entity = new CustomerPremisesDto();
            entity.setPremisesIds(premisesIds);
            cpList = customerPremisesService.selectCommissionByPremises(entity);

            getPremisesCommissionResDto.setResult(ResultEnum.SUCCESS.getNo());
            getPremisesCommissionResDto.setCpList(cpList);
            return getPremisesCommissionResDto;
        }catch (Exception e){
            getPremisesCommissionResDto.setResult(ResultEnum.FAIL.getNo());
            return getPremisesCommissionResDto;
        }
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/28
    *@param dto
    **/
    @Override
    public GetOrgCommissionPageResDto getOrgCommissionPage(GetOrgCommissionPageReqDto dto){
        GetOrgCommissionPageResDto  getOrgCommissionPageResDto = new GetOrgCommissionPageResDto();
        Page<CommissionDto> pageModel = new Page<CommissionDto>();
        try {
            PartnerInfo partnerInfo = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
            CommissionDto commissionDto = new CommissionDto();
            commissionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
            commissionDto.setDevCompanyId(partnerInfo.getHigherid());
            Map<String,Integer> map = PageUtil.getPageInfo(dto.getPageNo(), dto.getPageSize());
            commissionDto.setOrders("commission_status desc,pending_date");
            BeanUtils.copyProperties(dto,commissionDto);
            if(StringUtils.isNotBlank(dto.getAgentOrgId())){
            	commissionDto.setAgentCompanyId(Long.parseLong(dto.getAgentOrgId()));
            }
            pageModel = commissionService.getMyPageModel(commissionDto,map.get("startRow"),map.get("endRow"),partnerInfo.getAccountType(),dto.getUserId());
            pageModel.setPageNumber(dto.getPageNo());
            pageModel.setPageSize(dto.getPageSize());
            pageModel.setTotalPages(PageUtil.getTotalPage(new Integer(pageModel.getTotal()+""), dto.getPageSize()));
            getOrgCommissionPageResDto.setPage(pageModel);
            getOrgCommissionPageResDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch (YIXUNUNCheckedException e) {
            logger.error("分页信息失败: {}",e);
            pageModel = new Page<CommissionDto>();
            getOrgCommissionPageResDto.setResult(ResultEnum.FAIL.getNo());
            pageModel.setErrorMsg(e.getCode()+":"+e.getOutMsg());
            getOrgCommissionPageResDto.setPage(pageModel);
        }catch (Exception e) {
            getOrgCommissionPageResDto.setResult(ResultEnum.FAIL.getNo());
            logger.error("分页信息失败: {}",e);
            pageModel = new Page<CommissionDto>();
            pageModel.setErrorMsg(YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
            getOrgCommissionPageResDto.setPage(pageModel);
        }

        return getOrgCommissionPageResDto;
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/28
    *@param dto
    **/
    @Override
    public DealCommissionResDto dealCommission(DealCommissionReqDto dto){
        DealCommissionResDto dealCommissionResDto = new DealCommissionResDto();
        try {
            PartnerInfo partner = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
            if(dto.getCommissionId() == null || org.springframework.util.StringUtils.isEmpty(dto.getCommissionType()) || partner == null){
                dealCommissionResDto.setResult(ResultEnum.FAIL.getNo());
                dealCommissionResDto.setResultMsg("操作失败");
                return dealCommissionResDto;
            }
            Map<String,String> map = commissionService.dealCommission(dto.getCommissionId(),dto.getCommissionType(),dto.getCommission(),dto.getRemark(),partner.getId());
            if("1".equals(map.get("result"))){
                dealCommissionResDto.setResult(ResultEnum.SUCCESS.getNo());
                dealCommissionResDto.setResultMsg("操作成功");
            }else{
                dealCommissionResDto.setResult(ResultEnum.FAIL.getNo());
                dealCommissionResDto.setResultMsg("操作失败");
            }
        } catch (Exception e) {
            logger.error("结佣失败：{}",e);
            dealCommissionResDto.setResult(ResultEnum.FAIL.getNo());
            dealCommissionResDto.setResultMsg("结佣失败");
        }
        return dealCommissionResDto;
    }

    /**
    *@description 机构佣金结佣记录
    *@author sangtao
    *@date 2017/11/28
    *@param dto
    **/
    @Override
    public GetSettlementRecordResDto getSettlementRecord(GetSettlementRecordReqDto dto){
        GetSettlementRecordResDto getSettlementRecordResDto = new GetSettlementRecordResDto();
        try {
            CommissionDto commissionDto = commissionService.selectByMyId(dto.getId());
            BeanUtils.copyProperties(commissionDto,getSettlementRecordResDto);
            getSettlementRecordResDto.setResult(ResultEnum.SUCCESS.getNo());
        } catch (Exception e) {
            getSettlementRecordResDto.setResult(ResultEnum.FAIL.getNo());
            getSettlementRecordResDto.setResultMsg("系统异常");
        }
        return getSettlementRecordResDto;
    }

    /**
    *@description 添加佣金规则
    *@author sangtao
    *@date 2017/11/28
    *@param dto
    **/
    @Override
    public AddCRResDto addCR(AddCRReqDto dto){
        AddCRResDto addCRResDto = new AddCRResDto();
        CommissionRulesDto commissionRulesDto = new CommissionRulesDto();
        BeanUtils.copyProperties(dto,commissionRulesDto);
        try{
            //参数校验
            List<Company> listCompany = JSONObject.parseArray(dto.getCompany(),Company.class);
            if(dto.getRuleString() != null){
                List<RuleDto> listRules = JSONObject.parseArray(dto.getRuleString(),RuleDto.class);
                commissionRulesDto.setRules(listRules);
            }
            commissionRulesDto.setCooperations(listCompany);

            PartnerInfo pi = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
            // todo 校验参数

            //新增
            commissionRulesDto.setCreateUserId(pi.getId());
            commissionRulesDto.setCreateTime(Calendar.getInstance().getTime());
            int result = commissionRulesService.addCommissionRule(commissionRulesDto);
            if(result > 0){
                addCRResDto.setResult(ResultEnum.SUCCESS.getNo());
            }
        }catch (Exception e){
            logger.error("添加佣金规则失败: {}", e);
            addCRResDto.setResult(ResultEnum.FAIL.getNo());
            addCRResDto.setResultMsg("添加规则失败");
        }
        return addCRResDto;
    }
    /**
    *@description
    *@author sangtao
    *@date 2017/11/28
    *@param dto
    **/
    @Override
    public UpdateCRResDto updateCR(UpdateCRReqDto dto){
        UpdateCRResDto updateCRResDto = new UpdateCRResDto();
        CommissionRulesDto commissionRulesDto = new CommissionRulesDto();
        BeanUtils.copyProperties(dto,commissionRulesDto);
        try{
            PartnerInfo pi = partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
            // todo 校验参数

            if(dto.getRuleString() != null){
                List<RuleDto> listRules = JSONObject.parseArray(dto.getRuleString(),RuleDto.class);
                commissionRulesDto.setRules(listRules);
            }

            //新增
            commissionRulesDto.setUpdateUserId(pi.getId());
            commissionRulesDto.setUpdateTime(Calendar.getInstance().getTime());
            int result = commissionRulesService.editCommissionRule(commissionRulesDto);
            if(result > 0){
                updateCRResDto.setResult(ResultEnum.SUCCESS.getNo());
            }else{
                updateCRResDto.setResult(ResultEnum.FAIL.getNo());
                updateCRResDto.setResultMsg("编辑失败");
            }
        }catch (Exception e){
            logger.error("编辑规则异常：{}",e);
            updateCRResDto.setResult(ResultEnum.FAIL.getNo());
            updateCRResDto.setResultMsg("系统异常");
        }
        return updateCRResDto;
    }

    /**
    *@description
    *@author sangtao
    *@date 2017/11/28
    *@param dto
    **/
    @Override
    public GetCRDetailResDto getCRDetail(GetCRDetailReqDto dto){
       GetCRDetailResDto getCRDetailResDto = new GetCRDetailResDto();
       try {
           List<CommissionRuleParentDto> detail = commissionRuleParentService.getSetCommissionDetail(dto.getGroupId());
           if (detail != null && detail.size() > 0) {
               getCRDetailResDto.setResult(ResultEnum.SUCCESS.getNo());
               getCRDetailResDto.setCrDetail(detail);
               return getCRDetailResDto;
           }
       }catch (Exception e){
    	   logger.error("获取佣金明细失败: {}", e);
           getCRDetailResDto.setResult(ResultEnum.FAIL.getNo());
           getCRDetailResDto.setResultMsg(e.getMessage());
       }
        getCRDetailResDto.setResult(ResultEnum.FAIL.getNo());
        return getCRDetailResDto;
    }

    /**
     *@description
     *@author sangtao
     *@date 2017/11/29
     *@param dto
     **/
    @Override
    public ToUpdateCRResDto toUpdateCR(ToUpdateCRReqDto dto){
        ToUpdateCRResDto toUpdateCRResDto = new ToUpdateCRResDto();

        try {
            // 获取佣金数据
            CommissionRuleParent parent = commissionRuleParentService.getCommissionRule(dto.getRelationId());
            CommissionRulesDto commissionRulesDto = new CommissionRulesDto();
            BeanUtils.copyProperties(dto, commissionRulesDto);
            Map<String, Object> map = commissionRulesService.getCommissionRulesForEdit(commissionRulesDto);

            toUpdateCRResDto.setParent(parent);
            if (map.get("rules") != null) {
                toUpdateCRResDto.setListRules((List) map.get("rules"));
            }
            if (map.get("commission") != null) {
                toUpdateCRResDto.setCommission((CommissionRules) map.get("commission"));
            }
            toUpdateCRResDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch (Exception e ){
            logger.error("获取佣金规则异常: {}", e);
            toUpdateCRResDto.setResult(ResultEnum.FAIL.getNo());
            toUpdateCRResDto.setResultMsg("获取佣金规则异常");
        }
        return toUpdateCRResDto;

    }

    /**
    *@description 获取佣金规则列表
    *@author sangtao
    *@date 2017/12/4
    *@param dto
    **/
    @Override
    public GetCommissionSetPageResDto getCommissionSetPage(GetCommissionSetPageReqDto dto) {
        GetCommissionSetPageResDto getCommissionSetPageResDto = new GetCommissionSetPageResDto();
        Page<PremisesDto> page = new Page<PremisesDto>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            PartnerInfo pi =  partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
            PremisesDto premisesDto = new PremisesDto();
            premisesDto.setCompanyId(pi.getHigherid());
            premisesDto.setId(dto.getId());
            premisesDto.setCommissionMode(dto.getCommissionMode());
            premisesDto.setState(dto.getState());
            premisesDto.setId(dto.getPremisesId());
            premisesDto.setAgenCompanyId(dto.getAgentOrgId());
            if (StringUtils.isNotBlank(dto.getCreateTime())) {
                premisesDto.setCreateTime(new SimpleDateFormat("yyyy-MM-dd").parse(dto.getCreateTime()));
                String before = dto.getCreateTime() + " 00:00:00";
                String after = dto.getCreateTime() + " 23:59:59";
                try {
                    premisesDto.setCreateTimeBefore(sdf.parse(before));
                    premisesDto.setCreateTimeAfter(sdf.parse(after));
                } catch (Exception e) {
                    logger.error("getCommissionSetPage error: {}", e);
                }
            }
            Map<String, Integer> map = com.yixun.qfbao.util.PageUtil.getPageInfo(dto.getPageNo(), dto.getPageSize());
            page = premisesService.selectPremisesPageListWithRule(premisesDto, map.get("startRow"), map.get("endRow"),pi.getAccountType(),pi.getId());
            page.setPageNumber(dto.getPageNo());
            page.setPageInfo(page.getTotal(), map.get("startRow"),map.get("endRow")*dto.getPageNo());
            getCommissionSetPageResDto.setPage(page);
            getCommissionSetPageResDto.setResult(ResultEnum.SUCCESS.getNo());

        } catch (Exception e) {
            logger.error("获取佣金规则列表异常: {}", e);
            getCommissionSetPageResDto.setResult(ResultEnum.FAIL.getNo());
        }
        return getCommissionSetPageResDto;
    }

	@Override
	public GetCommissionModelResDto getCommissionModel(
			GetCommissionModelReqDto dto) {
		GetCommissionModelResDto res = new GetCommissionModelResDto();
		String no  = dto.getNo();
		String flag = dto.getFlag();
		Long staffId = dto.getStaffId();
		DateToEnum dateTo = DateToEnum.getByNo(no);
		String startTime = null;
		String endTime = null;
		if(dateTo!=null&&!dateTo.getNo().equals("0")){
			startTime=dateTo.getToDate()+" 00:00:00";
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			endTime = df.format(new Date())+" 23:59:59";
		}

		List<IndexRankingDto> pageList = indexBasicService.getCommissionModelPage(staffId,flag,startTime,endTime);
		PartnerInfo pi = partnerInfoService.selectById(staffId);
		Company company = companyService.selectById(pi.getHigherid());
		if("0".equals(company.getCommissionFlag())&&"1".equals(flag)){
			//将佣金相关的置为0
			for(IndexRankingDto index:pageList){
				index.setMoney("0");
			}
		}
		res.setIndexList(pageList);
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}

	/**
	*@description
	*@author sangtao
	*@date 2017/12/9
	*@param dto
	**/
	@Override
	public GetSettlementPageResDto getSettlementPage(GetSettlementPageReqDto dto){
        Page<CustomerPremisesDto> pageModel = new Page<CustomerPremisesDto>();
        GetSettlementPageResDto resDto = new GetSettlementPageResDto();
        Map<String,Integer> map = PageUtil.getPageInfo(dto.getPageNo(), dto.getPageSize());
        try {
            pageModel = customerPremisesService.getCommissionPageModel(dto.getId(), map.get("startRow"), map.get("endRow"));
            pageModel.setPageNumber(dto.getPageNo());
            pageModel.setPageSize(dto.getPageSize());
            pageModel.setTotalPages(PageUtil.getTotalPage(new Integer(pageModel.getTotal() + ""), dto.getPageSize()));
            resDto.setPage(pageModel);
            resDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch (Exception e){
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("获取佣金报备记录失败");
            logger.error("获取佣金报备记录失败: {}", e);
        }
        return resDto;
    }
    /**
    *@description 获取到处佣金规则的数据
    *@author sangtao
    *@date 2017/12/12
    *@param dto
    **/
    @Override
    public GetCommissionRuleExportResDto getCommissionRuleExport(GetCommissionRuleExportReqDto dto){
        GetCommissionRuleExportResDto getCommissionRuleExportResDto = new GetCommissionRuleExportResDto();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    try {
            Integer pageNo = 1;
            Integer pageSize = 10000;// 导出暂时设置成一万条
//            PartnerInfo pi = WebUtil.getPartnerInfo(request);
            PartnerInfo pi =  partnerInfoService.selectById(Long.parseLong(dto.getUserId()));
            PremisesDto premisesDto = new PremisesDto();
            premisesDto.setCompanyId(dto.getCompanyId());
            if(StringUtils.isNotEmpty(dto.getId())) {
            	premisesDto.setId(Long.valueOf(dto.getId()));
            }
            premisesDto.setAgenCompanyId(dto.getAgentOrgId());
            premisesDto.setCommissionMode(dto.getCommissionMode());
            premisesDto.setState(dto.getState());
            if (org.apache.commons.lang.StringUtils.isNotBlank(dto.getCreatTime())) {
                premisesDto.setCreateTime(new SimpleDateFormat("yyyy-MM-dd").parse(dto.getCreatTime()));
                String before = dto.getCreatTime() + " 00:00:00";
                String after = dto.getCreatTime() + " 23:59:59";
                try {
                    premisesDto.setCreateTimeBefore(sdf.parse(before));
                    premisesDto.setCreateTimeAfter(sdf.parse(after));
                } catch (Exception e) {
                    logger.error("getCommissionRuleExport error: {}", e);
                }
            }
            Map<String, Integer> map = com.yixun.qfbao.util.PageUtil.getPageInfo(pageNo, pageSize);
            Page<PremisesDto> page = premisesService.selectPremisesPageListWithRule(premisesDto, map.get("startRow"), map.get("endRow"),pi.getAccountType(),pi.getId());
            getCommissionRuleExportResDto.setPage(page);
            getCommissionRuleExportResDto.setResult(ResultEnum.SUCCESS.getNo());
        }catch (Exception e){
        	logger.error("导出佣金规则异常: {}", e);
            getCommissionRuleExportResDto.setResult(ResultEnum.FAIL.getNo());
            getCommissionRuleExportResDto.setResultMsg(e.getMessage());
        }
        return getCommissionRuleExportResDto;
    }
}
